import axios, {
  type AxiosResponse,
  type AxiosRequestConfig
} from "axios";
import pinia from "@/stores";
import { useUserInfoStore } from "@/stores/userInfo";

// 配置新建一个 axios 实例
const request = axios.create({
  /* import.meta.env:拿到环境变量对象 */
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 50000,
});

// 添加请求拦截器
request.interceptors.request.use((config: AxiosRequestConfig) => {
  const userInfoData = useUserInfoStore(pinia);
  config.url = `${config.url}${config.url?.split("?").length === 1 ? "?" : "&"}access_token=${userInfoData.access_token}`
  return config
});

// 添加响应拦截器
request.interceptors.response.use(
  /* 约束一下response */
  async (response: AxiosResponse) => {
    // 对响应数据做点什么
    return response.data
  },

);

export default request;
